import json
import dash
from dash import State
from dash import Input, Output, callback,html, dcc
import pandas as pd
import plotly.graph_objects as go
from flask import session
import os
from models import Organization
import plotly.express as px


#第2行第三列表格
def register_callbacks(dash_app):
    @dash_app.callback(
        [Output('branch-detail-preview-table', 'data'),
         Output('branch-result-count-display', 'children')],
        [Input('branch-detail-preview-button', 'n_clicks'),
         Input('branch-equipment-name-filter', 'n_submit'),
        Input('branch-equipment-name-filter', 'value')],
    )
    def filter_equipment_table(n_clicks, n_submit, filter_value):
        # 检查是否触发了回调
        ctx = dash.callback_context
        
        # 每次都从数据库获取完整数据
        from flask import session
        from models import Product, Organization
        
        # 获取当前机构信息
        org_code = session.get('current_org_code', session.get('user_org_code', ''))
        # print("当前机构代码:", org_code)
        
        # 初始化表格数据
        table_data = []
        
        if org_code:
            # 从数据库中查询属于当前机构的设备
            org = Organization.query.filter_by(org_code=org_code).first()
            # print("机构信息:", org)  # 打印机构信息以检查是否正确获取
            
            if org and org.short_name_c:
                # print("机构名称:", org.short_name_c)
                # 查询属于该机构的设备，按价格降序排列
                products = Product.query.filter_by(org_short_name_c=org.short_name_c).order_by(Product.price.desc()).all()
                
                for product in products:
                    # 计算年限指数（如果有service_life字段）
                    service_life = product.service_life or 0
                    year_index = round(service_life / 10, 2) if service_life else 0
                    
                    # 格式化价格为"xx.xx万元"
                    price_str = f"{product.price:.2f}万元" if product.price else "0.00万元"
                    
                    # 计算折旧金额（假设按照直线折旧法计算）
                    # 这里假设使用年限为10年，超过10年折旧为0
                    depreciation = product.price
                    if service_life < 10 and product.price:
                        depreciation = product.price * (1 - service_life / 10)
                    depreciation_str = f"{depreciation:.2f}万元" if depreciation is not None else "0.00万元"
                    mm = ""
                    if product.manufacturer :
                        mm +=  product.manufacturer
                    if product.model :
                        mm += product.model   
                    table_data.append({
                        '设备名称': product.product_name or '',
                        '设备型号':  mm ,
                        '设备金额': price_str,
                        '折旧金额': depreciation_str,
                        '年限指数': f"{year_index}",
                        'product_id': product.id  
                    })
        
        # 如果没有数据，使用默认数据
        if not table_data:
            table_data = [
                {'设备名称': '医用诊断DRX光机（工字型）', '设备型号': 'Q-Rad', '设备金额': '129.00万元', '折旧金额': '129.00万元', '年限指数': '1.73'},
                {'设备名称': '迈瑞彩超彩色多普勒超声系统', '设备型号': 'DC-80PRO', '设备金额': '78.20万元', '折旧金额': '72.02万元', '年限指数': '0.92'},
                {'设备名称': '全自动超声骨密度仪', '设备型号': 'VINNO E30', '设备金额': '49.80万元', '折旧金额': '49.80万元', '年限指数': '1.56'},
                {'设备名称': '迈瑞彩超彩色多普勒超声系统', '设备型号': 'M7', '设备金额': '48.00万元', '折旧金额': '44.21万元', '年限指数': '0.92'}
            ]
        
        # 如果没有触发回调或没有输入筛选条件，返回所有数据
        if not ctx.triggered or (not n_clicks and not n_submit) or not filter_value:
            return table_data, f"共 {len(table_data)} 条记录"
        
        # 根据输入的筛选条件过滤数据
        filtered_data = []
        filter_value = filter_value.lower()
        
        for item in table_data:
            # 检查设备名称和型号是否包含筛选条件
            if (filter_value in item['设备名称'].lower() or 
                filter_value in item['设备型号'].lower()):
                filtered_data.append(item)
        
        # 返回筛选后的数据和记录数量
        return filtered_data, f"共 {len(filtered_data)} 条记录"
    
    # 添加一个新的回调函数，用于更新明细预览链接的href属性
    @dash_app.callback(
        Output('branch-detail-preview-link', 'href'),
        Input('branch-detail-preview-link', 'id')  # 使用组件自身ID作为触发器
    )
    def update_detail_preview_link(_):
        # 获取当前机构信息
        org_code = session.get('current_org_code', session.get('user_org_code', ''))
        
        if org_code:
            # 从数据库中查询属于当前机构的信息
            org = Organization.query.filter_by(org_code=org_code).first()
            
            if org and org.short_name_c:
                # 返回带有org_short_name_c参数的URL
                return f"/dash/equipment?org_short_name_c={org.short_name_c}"
        
        # 如果没有获取到机构信息，返回不带参数的URL
        return "/dash/equipment"
    
    # 修改后的回调函数，用于处理表格行点击事件并在新页面打开
    
    # 使用 active_cell 方式实现点击单元格跳转
    dash_app.clientside_callback(
        """
        function(active_cell, table_data) {
            if (active_cell && table_data && table_data.length > 0) {
                const rowIndex = active_cell.row;
                const columnId = active_cell.column_id;
                
                // 获取点击行的数据
                const rowData = table_data[rowIndex];
                const productId = rowData['product_id'];
                
                console.log('点击的单元格:', active_cell);
                console.log('行数据:', rowData);
                console.log('设备ID:', productId);
                
                if (productId) {
                    // 自动在新标签页打开设备详情页面
                    const url = '/dash/equipment/detail?id=' + productId;
                    window.open(url, '_blank');
                    return '已打开设备详情页面 (设备ID: ' + productId + ')';
                } else {
                    return '未找到设备ID';
                }
            }
            return '';
        }
        """,
        Output('equipment-detail-output', 'children'),
        [Input('branch-detail-preview-table', 'active_cell')],
        [State('branch-detail-preview-table', 'data')]
    )
    
    # 在 register_callbacks 函数中添加以下回调
    @dash_app.callback(
        [Output(f"collapse-{i}", "is_open") for i in range(10)] +  # 假设最多10个类别
        [Output(f"icon-{i}", "className") for i in range(10)],
        [Input(f"collapse-button-{i}", "n_clicks") for i in range(10)],
        [State(f"collapse-{i}", "is_open") for i in range(10)]
    )
    def toggle_collapse(*args):
        ctx = dash.callback_context
        if not ctx.triggered:
            # 初始状态：所有折叠，所有图标为plus
            return [False] * 10 + ["fas fa-plus me-2"] * 10
        
        # 获取触发的按钮ID
        button_id = ctx.triggered[0]['prop_id'].split('.')[0]
        button_index = int(button_id.split('-')[-1])
        
        # 当前状态
        n_clicks_list = args[:10]
        current_states = args[10:]
        
        # 新的状态列表
        new_states = list(current_states)
        new_icons = ["fas fa-plus me-2"] * 10
        
        # 切换被点击的项目状态
        if n_clicks_list[button_index]:
            new_states[button_index] = not current_states[button_index]
        
        # 更新图标
        for i, is_open in enumerate(new_states):
            if is_open:
                new_icons[i] = "fas fa-minus me-2"
        
        return new_states + new_icons
    
    # 在 register_callbacks 函数中添加以下回调
    @dash_app.callback(
        [Output('equipment-analysis-graph', 'figure'),
         Output('equipment-btn', 'style'),
         Output('department-btn', 'style')],
        [Input('equipment-btn', 'n_clicks'),
         Input('department-btn', 'n_clicks')]
    )
    def update_analysis_chart(equipment_clicks, department_clicks):
        from flask import session
        from models import Product, Organization
        from datetime import datetime
        import plotly.graph_objects as go
        
        ctx = dash.callback_context
        
        # 确定当前模式
        mode = 'equipment'  # 默认设备模式
        if ctx.triggered:
            button_id = ctx.triggered[0]['prop_id'].split('.')[0]
            if button_id == 'department-btn':
                mode = 'department'
        
        # 按钮样式
        equipment_style = {'backgroundColor': '#4A90E2' if mode == 'equipment' else '#666', 
                          'color': 'white', 'border': 'none', 
                          'padding': '8px 16px', 'marginRight': '10px', 'borderRadius': '4px'}
        department_style = {'backgroundColor': '#4A90E2' if mode == 'department' else '#666', 
                           'color': 'white', 'border': 'none', 
                           'padding': '8px 16px', 'borderRadius': '4px'}
        
        # 获取当前机构信息
        org_code = session.get('current_org_code', session.get('user_org_code', ''))
        
        x_data = []
        y_data = []
        text_data = []
        sizes = []
        
        if org_code:
            org = Organization.query.filter_by(org_code=org_code).first()
            if org and org.short_name_c:
                # 查询属于该机构且有效的设备
                products = Product.query.filter_by(
                    org_short_name_c=org.short_name_c,
                    is_active=True
                ).all()
                
                current_date = datetime.now().date()
                
                if mode == 'equipment':
                    # 设备模式：每个设备一个点
                    for product in products:
                        if product.purchase_date and product.service_life and product.service_life > 0:
                            years_used = (current_date - product.purchase_date).days / 365.25
                            age_index = years_used / product.service_life
                            
                            if product.price and product.price > 0:
                                x_data.append(product.price)
                                y_data.append(age_index)
                                text_data.append(product.product_name or f'设备{product.id}')
                                sizes.append(max(10, min(50, product.price / 10)))
                    
                else:
                    # 科室模式：按科室计算平均值
                    department_data = {}
                    
                    for product in products:
                        if (product.purchase_date and product.service_life and 
                            product.service_life > 0 and product.price and product.price > 0):
                            
                            dept = product.department_name or '未分配科室'
                            years_used = (current_date - product.purchase_date).days / 365.25
                            age_index = years_used / product.service_life
                            
                            if dept not in department_data:
                                department_data[dept] = {'prices': [], 'age_indices': []}
                            
                            department_data[dept]['prices'].append(product.price)
                            department_data[dept]['age_indices'].append(age_index)
                    
                    # 计算每个科室的平均值
                    for dept, data in department_data.items():
                        if data['prices'] and data['age_indices']:
                            avg_price = sum(data['prices']) / len(data['prices'])
                            avg_age_index = sum(data['age_indices']) / len(data['age_indices'])
                            
                            x_data.append(avg_price)
                            y_data.append(avg_age_index)
                            text_data.append(dept)
                            sizes.append(max(15, min(60, len(data['prices']) * 5)))  # 根据设备数量设置大小
        
        # 如果没有数据，使用默认数据
        if not x_data:
            import numpy as np
            np.random.seed(42)
            x_data = np.random.uniform(10, 200, 20).tolist()
            y_data = np.random.uniform(0, 2, 20).tolist()
            text_data = [f'设备{i+1}' if mode == 'equipment' else f'科室{i+1}' for i in range(20)]
            sizes = [20] * 20
        
        fig = go.Figure()
        
        fig.add_trace(go.Scatter(
            x=x_data,
            y=y_data,
            mode='markers',
            marker=dict(
                size=sizes,
                color=['#00d4ff', '#00ff88', '#ffaa00', '#ff6b6b'] * (len(x_data)//4 + 1),
                opacity=0.7,
                line=dict(width=1, color='white')
            ),
            text=text_data,
            hovertemplate='<b>%{text}</b><br>价格: %{x:.2f}万元<br>年限指数: %{y:.2f}<extra></extra>'
        ))
        
        fig.update_layout(
            title=dict(
                text="",
                font=dict(color='white', size=16),
                x=0.05,
                y=0.95,
                xanchor='left',
                yanchor='top'
            ),
            xaxis=dict(
                title=dict(
                    text="价格(万元)",
                    font=dict(color='white')
                ),
                tickfont=dict(color='white'),
                gridcolor='#2a3f7a'
            ),
            yaxis=dict(
                title=dict(
                    text="年限指数",
                    font=dict(color='white')
                ),
                tickfont=dict(color='white'),
                gridcolor='#2a3f7a'
            ),
            paper_bgcolor='rgba(0,0,0,0)',
            plot_bgcolor='#1a2b5c',
            margin=dict(t=20, b=20, l=60, r=60),
            height=415
        )
        
        return fig, equipment_style, department_style


    
   